import { MciButton, MciSelect } from '@/components/base';
import { useFormMode } from '@/components/base/Form/mode';
import { TableForm, Td, Tr } from '@/components/base/TableForm';
import { Conditions } from '@/components/business/Conditions';
import { CalcTypeWithValueSelector } from '@/components/business/DictSelector/CalcType';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useDictStore } from '@/store/dict';
import { ElForm, ElFormItem } from 'element-plus';
import { PropType } from 'vue';
import { TRuleItem } from '../../../types';
import { RowIndex } from '../../RowIndex';
import './index.scss';

export const ConditionAssignment = defineComponent({
  props: {
    data: {
      type: [Array] as PropType<TRuleItem[]>,
      default: () => []
    },
    noAssignment: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:data'],
  setup(props, { expose, emit }) {
    const currentNode = useCurrentNode();
    const dictStore = useDictStore();
    const assignmentList = ref<TRuleItem[]>([]);
    const formMode = useFormMode();

    const addConditionAssignment = () => {
      assignmentList.value.push({
        conditions: { conditions: [{}], conjs: [] } as any,
        assignments: [{ rightType: 'CONSTANT' }] as any,
        ruleName: ''
      });
    };

    const defaultConditionAssignment = () => {
      assignmentList.value.push({
        conditions: { conditions: [] as any, conjs: [] as any } as any,
        assignments: [{ rightType: 'CONSTANT' }] as any,
        ruleName: ''
      });
    };

    watchEffect(() => {
      assignmentList.value = props.data;
    });

    watch(
      assignmentList,
      () => {
        emit('update:data', assignmentList.value);
        currentNode.saveCondition(assignmentList.value);
      },
      { deep: true }
    );

    onMounted(() => {
      if (props.noAssignment && props.data.length === 0) {
        defaultConditionAssignment();
      } else {
        assignmentList.value = props.data;
      }
    });

    expose({
      addConditionAssignment
    });

    return () => {
      const variableOptions = currentNode.currentAndParentPrivateVariablesOptions.value.concat(
        currentNode.currentAndParentNodeVariablesOptions.value
      );

      const variableOptionsWithSystem = dictStore.systemVarsOptions.concat(variableOptions);

      // 复制操作
      const copyRow = (index: number) => {
        const child =
          index < assignmentList.value.length - 2
            ? document.querySelector(`.ruleScrollId .row-index-assignment-item:nth-child(${index + 1})`)
            : document.querySelector(`.row-index-assignment-last-item`);
        if (child) {
          setTimeout(() => {
            child.scrollIntoView({ behavior: 'smooth' });
          }, 1);
        }
      };

      return (
        <TableForm>
          <div>
            {assignmentList.value.map((item, index) => {
              return (
                <div class="row-index-assignment-item">
                  <RowIndex
                    index={index}
                    v-model:list={assignmentList.value}
                    noAssignment={props.noAssignment}
                    hasCopy={true}
                    onCopy={copyRow}>
                    <ElForm>
                      <Tr>
                        <Td span={!props.noAssignment ? 14 : 24} class=" text-left bg-gray-100 py-12 pl-12">
                          条件配置
                        </Td>
                        {!props.noAssignment && (
                          <Td span={10} class=" text-left bg-gray-100 py-12 pl-12">
                            赋值
                          </Td>
                        )}
                      </Tr>
                      <Tr class="pt-8 pb-30 condition-item">
                        <Td span={!props.noAssignment ? 14 : 24} class="flex if flex-col relative">
                          <div class="flex flex-col relative condition-item-detail mr-16">
                            <Conditions
                              modelValue={item.conditions || {}}
                              onUpdate:modelValue={(val) => {
                                item.conditions = val;
                              }}
                              class="flex-1"
                              variableOptions={variableOptions}
                              leftOptions={variableOptionsWithSystem}
                            />
                          </div>
                        </Td>
                        {props.noAssignment ? null : (
                          <Td span={10} class="result flex flex-col pl-12 mt-12 relative">
                            {item.assignments?.map((assignment, assignmentIndex) => {
                              return (
                                <RowIndex
                                  hasNum={false}
                                  index={assignmentIndex}
                                  onDelete={(deleteIndex: number) => {
                                    assignmentList.value[index].assignments?.splice(deleteIndex, 1);
                                  }}>
                                  <div class="flex gap-8">
                                    <ElFormItem class={'shrink-0'} style={{maxWidth: '30%'}}>
                                      <MciSelect
                                        v-model={assignment.left}
                                        list={variableOptionsWithSystem}
                                        placeholder="请选择"
                                        filterable={true}
                                        onChange={(val: any) => {
                                          const variable = variableOptionsWithSystem.find((item: any) => item.value === val);
                                          if (variable) {
                                            const varType = variable.varType;
                                            if (item.assignments && item.assignments[assignmentIndex]) {
                                              item.assignments[assignmentIndex].varType = varType;
                                            }
                                          }
                                        }}
                                      />
                                    </ElFormItem>

                                    <ElFormItem class="grow" >
                                      <CalcTypeWithValueSelector
                                        fieldTypeDisabled={true}
                                        varType={assignment.varType}
                                        left={assignment.left}
                                        withFieldType
                                        variableOptions={variableOptionsWithSystem}
                                        modelValue={{
                                          calcType: assignment.rightType,
                                          fieldType: assignment.rightFieldType,
                                          value: assignment.right
                                        }}
                                        onUpdate:modelValue={(val) => {
                                          item.assignments![assignmentIndex] = {
                                            left: assignment.left,
                                            right: val.value,
                                            rightType: val.calcType,
                                            rightFieldType: val.fieldType,
                                            varType: assignment.varType
                                          };
                                        }}
                                      />
                                    </ElFormItem>
                                  </div>
                                </RowIndex>
                              );
                            })}
                            {formMode?.mode === 'edit' && (
                              <div>
                                <MciButton
                                  link
                                  icon="mci-icon-add"
                                  onClick={() => {
                                    item.assignments!.push({
                                      rightType: 'CONSTANT'
                                    } as any);
                                  }}>
                                  添加赋值
                                </MciButton>
                              </div>
                            )}
                          </Td>
                        )}
                      </Tr>
                    </ElForm>
                  </RowIndex>
                </div>
              );
            })}
          </div>
          <div class="row-index-assignment-last-item"></div>
        </TableForm>
      );
    };
  }
});
